﻿using Microsoft.VisualBasic;
using minidwm.Model;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace minidwm
{
    public partial class StockFrom : Form
    {
        private AppSetting _appSetting; // 应用程序设置
        private Random random = new Random(); // 随机数生成器
        private int randomInt; // 随机数
        private DateTime startTime; // 开始时间
        private DateTime tipTime; // 提示时间

        public StockFrom()
        {
            InitializeComponent();

            // 获取应用程序的根目录
            string appDirectory = tb_AppSettingPath.Text;
            try
            {
                // 构建JSON文件的完整路径
                string jsonFilePath = Path.Combine(appDirectory, "appsetting.json");
                string jsonContent = File.ReadAllText(jsonFilePath);

                // 反序列化JSON内容为AppSetting对象
                _appSetting = JsonConvert.DeserializeObject<AppSetting>(jsonContent);
            }
            catch (FileNotFoundException ffe)
            {
                MessageBox.Show($"{appDirectory}JSON文件未找到，请检查文件路径。{ffe.Message}");
            }
            catch (JsonReaderException ex)
            {
                MessageBox.Show($"JSON文件格式错误：{ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"读取JSON文件时发生错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 开始/停止按钮点击事件
        /// </summary>
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (!timer_Stock.Enabled)
            {
                btn_start.Text = "取消";
                timer_Stock.Enabled = true;
                startTime = DateTime.Now;
            }
            else
            {
                btn_start.Text = "启动";
                timer_Stock.Enabled = false;
                startTime = DateTime.Now;
            }
        }

        /// <summary>
        /// 设置按钮点击事件
        /// </summary>
        private void btn_Setting_Click(object sender, EventArgs e)
        {
            Hide();
            Formshutdown formshutdown = new Formshutdown();
            formshutdown.Show();
        }

        /// <summary>
        /// 定时器事件，每秒触发一次
        /// </summary>
        private void timer_Stock_Tick(object sender, EventArgs e)
        {
            DateTime currentTime = DateTime.Now; // 当前时间
            // 判断是否是周末，或者是15点以后
            if (currentTime.Hour >= 15 || currentTime.DayOfWeek == DayOfWeek.Saturday || currentTime.DayOfWeek == DayOfWeek.Sunday)
            {
                btn_start_Click(sender, e);
                MessageBox.Show("已经停市了！");
                return;
            }

            if (!int.TryParse(tbtime.Text.Trim(), out int times))
            {
                MessageBox.Show("请输入有效的数字时间！");
                return;
            }

            long timeElapsed = (long)(startTime - currentTime).TotalSeconds; // 已经过的时间（秒）
            try
            {
                randomInt = random.Next(0, 5); // 生成随机数
                long timeLong = times * 60; // 总时间（秒）
                if (timeElapsed < timeLong)
                {
                    // 计算当前进度，并更新进度条
                    double progress = 100 - ((double)timeElapsed / timeLong) * 100;
                    if (progress > 100)
                        progress = 100;
                    else if (progress <= 0)
                        progress = 0;
                    pb_time.Value = (int)progress;
                }

                if (timeElapsed == 0)
                {
                    var stockCodeList = _appSetting.StockCodeList.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    int index = 1;
                    dgv_Content.Rows.Clear();
                    foreach (var item in stockCodeList)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            SetStockInfo(item, index++);
                        }
                    }
                    startTime = startTime.AddMinutes(times).AddSeconds(randomInt); // 更新开始时间
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show($"请求异常:{ex.Message}");
                this.btn_start.Text = "启动";
                this.timer_Stock.Enabled = false;
            }
        }

        /// <summary>
        /// 设置股票信息
        /// </summary>
        public void SetStockInfo(string stockCode = "000066", int index = 1)
        {
            tipTime = DateTime.Now; // 更新提示时间
            // 处理股票信息
            if (string.IsNullOrEmpty(stockCode))
            {
                MessageBox.Show("请输入股票代码！");
                return;
            }

            // 根据股票代码前缀设置前缀
            if (stockCode.StartsWith("6") || stockCode.StartsWith("5"))
            {
                stockCode = "1." + stockCode;
            }
            else if (stockCode.StartsWith("0") || stockCode.StartsWith("3"))
            {
                stockCode = "0." + stockCode;
            }
            string url = $"https://push2.eastmoney.com/api/qt/stock/get?secid={stockCode}&fields=f57,f58,f42,f43,f44,f45,f46,f60";
            string result = HttpHepler.HttpGet(url, Encoding.UTF8);
            StockResult resultData = JsonConvert.DeserializeObject<StockResult>(result, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });

            if (resultData?.Data == null)
            {
                MessageBox.Show($"{stockCode}股票代码有误");
                return;
            }
            else
            {

                lb_time.Text = DateTime.Now.ToString();
                decimal nowPice = (decimal)resultData.Data.F43 / 100; // 最新价格
                decimal maxPice = (decimal)resultData.Data.F44 / 100; // 最高价格
                decimal minPice = (decimal)resultData.Data.F45 / 100; // 最低价格
                decimal todayPice = (decimal)resultData.Data.F46 / 100; // 今开价格
                decimal yesterdayPic = (decimal)resultData.Data.F60 / 100; // 昨天收盘价
                string name = resultData.Data.F58; // 股票名称
                string code = resultData.Data.F57; // 股票代码
                decimal difference = nowPice - yesterdayPic; // 差价
                decimal increase = Math.Round((difference / yesterdayPic) * 100, 2); // 涨跌幅百分比

                dgv_Content.Rows.Add(name, code, maxPice, minPice, nowPice, $"{increase}%");
                dgv_Content.Rows[index - 1].Cells[5].Style.BackColor = increase > 0 ? System.Drawing.Color.Red : System.Drawing.Color.Green;

                TipTime(name, increase, _appSetting.Increase, _appSetting.TipTime); // 设置提示信息
            }
        }

        /// <summary>
        /// 设置股票提示信息
        /// </summary>
        private void TipTime(string name, decimal increase, int increaseTip = 3, int tipInterval = 5)
        {
            if (increaseTip <= 0)
            {
                increaseTip = 3; // 默认涨跌幅提示值
            }

            DateTime currentTime = DateTime.Now; // 当前时间
            long timeElapsed = (long)(currentTime - tipTime).TotalSeconds; // 计算时间差（秒）

            // 判断是否需要提示
            if ((increase > increaseTip || increase < -increaseTip) && timeElapsed <= 0)
            {
                noIcon.Visible = true; // 设置提示控件可见
                string message = increase > 0 ? $"涨了{increase}%，可以考虑卖出" : $"跌了{increase}%，准备买入";
                noIcon.ShowBalloonTip(10000, name, message, ToolTipIcon.Info); // 显示气泡提示
                tipTime = currentTime.AddMinutes(tipInterval).AddSeconds(randomInt); // 更新提示时间
            }
        }
    }
}